<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="时间范围" prop="dateRange">
        <el-date-picker
          v-model="queryParams.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="答卷地区" prop="region">
        <el-select
          v-model="queryParams.region"
          placeholder="请选择答卷地区"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="region in regionOptions"
            :key="region"
            :label="region"
            :value="region"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="来源网站" prop="source">
        <el-select
          v-model="queryParams.source"
          placeholder="请选择来源网站"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="source in sourceOptions"
            :key="source"
            :label="source"
            :value="source"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="答卷内容" prop="searchText">
        <el-input
          v-model="queryParams.searchText"
          placeholder="请输入答卷内容"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button type="primary" plain @click="exportToExcel">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 卡片列表 -->
  <ContentWrap>
    <div class="cards-grid">
      <el-card v-for="(answer, index) in pagedAnswers" :key="index" class="answer-card">
        <template #header>
          <div class="card-header">
            <span>答卷 #{{ answer.id }}</span>
            <el-tag :type="getStatusType(answer.status)">
              {{ answer.status }}
            </el-tag>
          </div>
        </template>
        <div class="card-content">
          <div class="answer-info">
            <p><strong>时间：</strong>{{ formatTime(answer.submitTime) }}</p>
            <p><strong>地区：</strong>{{ answer.region }}</p>
            <p><strong>来源：</strong>{{ answer.source }}</p>
          </div>
          <el-divider />
          <div class="answer-details">
            <h4>答卷内容：</h4>
            <div v-for="(item, qIndex) in answer.questions" :key="qIndex" class="question-item">
              <p
                ><strong>{{ item.question }}</strong></p
              >
              <p>{{ item.answer }}</p>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
</template>

<script setup lang="ts">
import * as XLSX from 'xlsx'
// 模拟数据
const answerList = ref([
  {
    id: 1,
    status: '已完成',
    submitTime: '2025-08-18T09:30:00',
    region: '南宁市',
    source: '微信',
    questions: [
      { question: '您的年龄？', answer: '12岁' },
      { question: '您的所处学段？', answer: '小学' }
    ]
  },
  {
    id: 2,
    status: '已完成',
    submitTime: '2025-08-18T14:15:00',
    region: '柳州市',
    source: '企业微信',
    questions: [
      { question: '您的年龄？', answer: '10岁' },
      { question: '您的所处学段？', answer: '小学' }
    ]
  },
  {
    id: 3,
    status: '未完成',
    submitTime: '2025-08-18T11:45:00',
    region: '桂林市',
    source: '直接访问',
    questions: [
      { question: '您的年龄？', answer: '15岁' },
      { question: '您的所处学段？', answer: '初中' }
    ]
  },
  {
    id: 4,
    status: '已完成',
    submitTime: '2025-08-17T16:20:00',
    region: '梧州市',
    source: 'QQ',
    questions: [
      { question: '您的年龄？', answer: '13岁' },
      { question: '您的所处学段？', answer: '初中' }
    ]
  },
  {
    id: 5,
    status: '已拒绝',
    submitTime: '2025-08-17T10:10:00',
    region: '北海市',
    source: '微博',
    questions: [
      { question: '您的年龄？', answer: '18岁' },
      { question: '您的所处学段？', answer: '高中' }
    ]
  },
  {
    id: 6,
    status: '已完成',
    submitTime: '2025-08-17T08:45:00',
    region: '防城港市',
    source: '微信',
    questions: [
      { question: '您的年龄？', answer: '16岁' },
      { question: '您的所处学段？', answer: '高中' }
    ]
  },
  {
    id: 7,
    status: '已完成',
    submitTime: '2025-08-17T13:30:00',
    region: '钦州市',
    source: '企业微信',
    questions: [
      { question: '您的年龄？', answer: '18岁' },
      { question: '您的所处学段？', answer: '大学' }
    ]
  },
  {
    id: 8,
    status: '已完成',
    submitTime: '2025-08-17T15:20:00',
    region: '贵港市',
    source: 'QQ',
    questions: [
      { question: '您的年龄？', answer: '20岁' },
      { question: '您的所处学段？', answer: '大学' }
    ]
  },
  // 新增的5条数据
  {
    id: 9,
    status: '已完成',
    submitTime: '2025-08-17T09:30:00',
    region: '玉林市',
    source: '抖音',
    questions: [
      { question: '您的年龄？', answer: '20岁' },
      { question: '您的所处学段？', answer: '大学' }
    ]
  },
  {
    id: 10,
    status: '未完成',
    submitTime: '2025-08-17T14:15:00',
    region: '百色市',
    source: '快手',
    questions: [
      { question: '您的年龄？', answer: '22岁' },
      { question: '您的所处学段？', answer: '大学' }
    ]
  },
  {
    id: 11,
    status: '已完成',
    submitTime: '2025-08-18T11:45:00',
    region: '河池市',
    source: '小红书',
    questions: [
      { question: '您的年龄？', answer: '33岁' },
      { question: '您的所处学段？', answer: '建筑师' }
    ]
  },
  {
    id: 12,
    status: '已拒绝',
    submitTime: '2025-08-18T16:20:00',
    region: '贺州市',
    source: 'B站',
    questions: [
      { question: '您的年龄？', answer: '19岁' },
      { question: '您的所处学段？', answer: '大学生' }
    ]
  },
  {
    id: 13,
    status: '已完成',
    submitTime: '2025-08-18T10:10:00',
    region: '来宾市',
    source: '知乎',
    questions: [
      { question: '您的年龄？', answer: '41岁' },
      { question: '您的所处学段？', answer: '律师' }
    ]
  }
])

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  dateRange: [],
  region: '',
  source: '',
  searchText: ''
})

const total = ref(answerList.value.length)
const queryFormRef = ref()
const filteredAnswers = ref([...answerList.value])

// 获取所有地区选项
const regionOptions = computed(() => {
  return [...new Set(answerList.value.map((item) => item.region))]
})

// 获取所有来源网站选项
const sourceOptions = computed(() => {
  return [...new Set(answerList.value.map((item) => item.source))]
})

// 格式化时间
const formatTime = (time) => {
  return new Date(time).toLocaleString()
}

// 根据状态返回不同的标签样式
const getStatusType = (status) => {
  const statusMap = {
    已完成: 'success',
    未完成: 'warning',
    已拒绝: 'danger'
  }
  return statusMap[status] || 'info'
}

/** 查询列表 */
const getList = () => {
  filteredAnswers.value = answerList.value.filter((answer) => {
    // 日期筛选（修复版）
    if (queryParams.dateRange && queryParams.dateRange.length === 2) {
      const startDate = new Date(queryParams.dateRange[0])
      startDate.setHours(0, 0, 0, 0) // 设置为当天开始时间

      const endDate = new Date(queryParams.dateRange[1])
      endDate.setHours(23, 59, 59, 999) // 设置为当天结束时间

      const answerDate = new Date(answer.submitTime)

      if (answerDate < startDate || answerDate > endDate) {
        return false
      }
    }

    // 地区筛选
    if (queryParams.region && answer.region !== queryParams.region) {
      return false
    }

    // 来源网站筛选
    if (queryParams.source && answer.source !== queryParams.source) {
      return false
    }

    // 内容搜索
    if (queryParams.searchText) {
      const searchStr = queryParams.searchText.toLowerCase()
      return (
        answer.id.toString().toLowerCase().includes(searchStr) ||
        answer.region.toLowerCase().includes(searchStr) ||
        answer.source.toLowerCase().includes(searchStr) ||
        answer.questions.some(
          (q) =>
            q.question.toLowerCase().includes(searchStr) ||
            q.answer.toLowerCase().includes(searchStr)
        )
      )
    }

    return true
  })

  total.value = filteredAnswers.value.length
}

/** 导出Excel */
const exportToExcel = () => {
  // 准备导出的数据
  const exportData = filteredAnswers.value.map((answer) => {
    // 将问题列表转换为字符串格式
    const questionsStr = answer.questions.map((q) => `${q.question}: ${q.answer}`).join('\n')
    return {
      // ID: answer.id,
      状态: answer.status,
      提交时间: formatTime(answer.submitTime),
      地区: answer.region,
      来源网站: answer.source,
      答卷内容: questionsStr
    }
  })
  console.log(exportData, 88888)
  // 创建工作表
  const worksheet = XLSX.utils.json_to_sheet(exportData)
  // 创建工作簿
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, '答卷数据')
  // 生成Excel文件并下载
  const dateStr = new Date().toISOString().slice(0, 10)
  XLSX.writeFile(workbook, `答卷数据_${dateStr}.xlsx`)
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.pageNo = 1
  filteredAnswers.value = [...answerList.value]
  total.value = answerList.value.length
}

// 分页数据
const pagedAnswers = computed(() => {
  const start = (queryParams.pageNo - 1) * queryParams.pageSize
  const end = start + queryParams.pageSize
  return filteredAnswers.value.slice(start, end)
})

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
.cards-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 20px;

  .answer-card {
    height: 100%;
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .answer-info p {
      margin: 5px 0;
    }

    .question-item {
      padding: 8px;
      margin-bottom: 10px;
      background-color: #f9f9f9;
      border-radius: 4px;
    }
  }
}
</style>
